package com.free.ext.aliababa;

import com.alibaba.fastjson.JSONObject;
import com.free.utils.AlHttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import sun.misc.BASE64Encoder;

import java.util.HashMap;
import java.util.Map;

public class AlibabaSdkOcr {
    //拼装请求的字符串
    public static JSONObject getJosnString(byte[] content, String config_str) throws Exception {
        // 对图像进行base64编码
        BASE64Encoder base64Encoder =new BASE64Encoder();
        String imgBase64 = base64Encoder.encode(content);
        imgBase64 = imgBase64.replaceAll("\\r\\n","");
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
            requestObj.put("image", imgBase64);
            if(config_str.length() > 0) {
                requestObj.put("configure", config_str);
        }
        return requestObj;
    }

    //访问解析接口
    public static HttpResponse postOperation(String host, String path, String appcode, String bodys) throws Exception {
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        Map<String,String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        String method = "post";
        HttpResponse response = AlHttpUtils.doPost(host,path,method,headers,querys,bodys);
        int stat = response.getStatusLine().getStatusCode();
        if(stat != 200){
            System.out.println("Http code: " + stat);
            System.out.println("http header error msg: "+ response.getFirstHeader("X-Ca-Error-Message"));
            System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
            return null;
        }
        return response;
    }
}
